package com.example.origin.demo.demo;


import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RequestMapping("ThreadLocalDemo")
@RestController
public class ThreadLocalDemo {

    @GetMapping("test")
    public void test() throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1));

        ThreadLocal local = new InheritableThreadLocal();
        local.set(1);


        executor.execute(() -> {
            System.out.println("打印1:" + local.get());
        });

        TimeUnit.SECONDS.sleep(2);

        local.set(2);

        System.out.println("打印2:" + local.get());

        executor.execute(() -> {
            System.out.println("打印3:" + local.get());
        });

    }

    @GetMapping("test2")
    public void test2() {
        ExecutorService TTLExecutor = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(5));
        //定义另外一个线程池循环执行，模拟业务场景下多Http请求调用的情况
        ExecutorService loopExecutor = Executors.newFixedThreadPool(5);
        AtomicInteger i = new AtomicInteger(0);
        //TTL的ThreadLocal
        ThreadLocal tl = new TransmittableThreadLocal<>(); //这里采用TTL的实现


        while (i.get()<10) {

            loopExecutor.execute(() -> {
                if (i.get() < 10) {
                    tl.set(i.getAndAdd(1));
                    TTLExecutor.execute(() -> {
                       log.info(String.format("子线程名称-%s, 变量值=%s", Thread.currentThread().getName(), tl.get()));
                    });
                }
            });
        }


    }

}
